﻿// 
// Salient.Web 
// (c) 2009 Sky Sanders (sky.sanders@gmail.com)
// Licensed under the Microsoft Public License (Ms-PL)
// 
using System;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;

namespace Salient.Web
{
    public class HTTPHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request["delay"] != null)
            {
                DateTime endTime = DateTime.Now.AddMilliseconds(Convert.ToInt32(context.Request["delay"]));
                while (DateTime.Now < endTime)
                {
                    // noop
                }
            }

            TestObj obj = null;
            string contentType = context.Request.ContentType.ToLower();
            // posting json
            if (contentType.StartsWith("application/json") || contentType.StartsWith("text/json"))
            {
                using (StreamReader reader = new StreamReader(context.Request.InputStream))
                {
                    string input = reader.ReadToEnd();

                    JavaScriptSerializer js = new JavaScriptSerializer();
                    obj = (new JavaScriptSerializer()).Deserialize<TestObj>(input);
                }
            }
            else
            {
                // get and form post
                if (context.Request.QueryString["name"] != null || context.Request["name"] != null)
                {
                    obj = new TestObj(context.Request.QueryString["name"] ?? context.Request["name"]);
                }
            }


            if (obj != null)
            {
                context.Response.Clear();
                context.Response.ContentType = "text/json";
                context.Response.Write((new JavaScriptSerializer()).Serialize(obj));
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        #endregion
    }
}